package com.ycrlkj.android.modulescore.main.activity.app;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.ycrlkj.android.modulesbase.libbase.utils.PhoneUtil;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.apiservice.NoauthApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityLoginBinding;
import com.ycrlkj.android.modulescore.main.entity.User;
import com.ycrlkj.android.modulescore.main.viewmodel.LoginViewModel;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_LOGIN)
public class LoginActivity extends AppCompatActivity {

    private ActivityLoginBinding binding;
    private LoginViewModel viewModel;

    @Inject
    NoauthApiService noauthApiService;

    private Handler countDownHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);

        setContentView(binding.getRoot());
    }


    public void toHome() {
        finish();
        ARouter.getInstance().build(RoutePath.PAGE_HOME).navigation();
    }

    public void handleToAgreement(View view) {
        ARouter.getInstance().build(RoutePath.PAGE_AGREEMENT).navigation();
    }

    public void handleAgree(View view) {
        Boolean bool = viewModel.getAgree().getValue();
        viewModel.getAgree().setValue(!bool);
    }

    public void handleLoginType(View view) {
        int tag = Integer.parseInt((String)view.getTag());
        viewModel.getLoginType().setValue(tag);
    }

    public void handleToRegister(View view) {
        ARouter.getInstance().build(RoutePath.PAGE_REGISTER).navigation();
    }

    public void handleCallServicePhone(View view) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        String servicePhone = getString(R.string.servicePhone);
        intent.setData(Uri.parse("tel:" + servicePhone));
        startActivity(intent);
    }

    public void handleCheckUpdate(View view) {
        //todo
        //检查更新

        XPopupUtil.showModal(this, "发现新版本, 现在更新?", new OnConfirmListener() {
            @Override
            public void onConfirm() {
                ToastUtils.showLong("更新成功");
            }
        });
    }


    public void handleLogin(View view) {

        int loginType = viewModel.getLoginType().getValue();

        String phone = viewModel.getPhone().getValue();
        String passwordOrSmsCode = viewModel.getPasswordOrSmsCode().getValue();

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong("手机号必须填写");
            return;
        }

        if (!PhoneUtil.isMobileNumberEasy(phone)) {
            ToastUtils.showLong("请填写正确的手机号");
            return;
        }

        if (loginType == 2) {
            if (TextUtils.isEmpty(passwordOrSmsCode)) {
                ToastUtils.showLong("验证码必须填写");
                return;
            }
            if (passwordOrSmsCode.length() != 4) {
                ToastUtils.showLong("验证码应为4位数字");
                return;
            }
        } else {
            if (TextUtils.isEmpty(passwordOrSmsCode)) {
                ToastUtils.showLong("密码必须填写");
                return;
            }

            if (passwordOrSmsCode.length() < 6) {
                ToastUtils.showLong("密码至少6位");
                return;
            }
        }

        boolean agree = viewModel.getAgree().getValue();
        if (!agree) {
            XPopupUtil.showAlert(this, "请阅读并同意[用户隐私政策]");
            return;
        }

        User form = new User();
        form.setPhone(phone);
        form.setPassword(passwordOrSmsCode);

        login(form);
    }

    @SuppressLint("CheckResult")
    public void login(User form) {
        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this);
        XPopupUtil.hideLoadingDelay(loadingPopupView);

        noauthApiService.login(form, viewModel.getLoginType().getValue())
                .compose(ResponseTransformer.obtain())
                .subscribe(user -> {
                    XPopupUtil.hideLoading(loadingPopupView);

                    SPStaticUtils.put("token", user.getToken());
                    SPStaticUtils.put("userId", user.getId());
                    SPStaticUtils.put("userName", user.getName());
                    SPStaticUtils.put("user", JSON.toJSONString(user));

                    toHome();

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(LoginActivity.this, e);
                    }
                });

    }

    @SuppressLint("CheckResult")
    public void handleSendSmsCode(View view) {
        String phone = viewModel.getPhone().getValue();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong("手机号必须填写");
            return;
        }

        noauthApiService.sendSmsCode(phone)
                .compose(ResponseTransformer.obtain())
                .subscribe(resultData -> {
                    ToastUtils.showLong(resultData.getToast());

                    countDownHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Integer wait = viewModel.getSendSmsCodeWait().getValue();
                            wait--;
                            if (wait <= 0) {
                                viewModel.getSendSmsCodeWait().setValue(60);//重置 wait = 60
                            } else {
                                viewModel.getSendSmsCodeWait().setValue(wait);
                                countDownHandler.postDelayed(this, 1000);//调用自身
                            }
                        }
                    }, 1000);//每秒执行一次runnable

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(LoginActivity.this, e);
                    }
                });

    }


    //应用程序首页需重写返回按钮事件, 阻止按一次返回键就直接退出程序, 需询问用户是否退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //此处弹窗是由返回按钮触发, .dismissOnBackPressed(false)必须为false, 否则有bug, 弹窗刚出现就被关闭
            XPopupUtil.showModal(this, "确定要退出程序吗?", false, new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    finish();
                }
            });

            return true;
        } else {
            //如果按下的不是返回按钮, 则执行按钮默认操作
            return super.onKeyDown(keyCode, event);
        }
    }

}